﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PermutationCipher.Models
{
    /// <summary>
    /// 解密类
    /// </summary>
    internal class MyDecode
    {
        /// <summary>
        /// 明文
        /// </summary>
        public string PlainText { get; set; }
        /// <summary>
        /// 密文
        /// </summary>
        public string CipherText { get; set; }
        /// <summary>
        /// 密钥
        /// </summary>
        public string Key { get; set; }
        public void Decode()
        {
            //解密
            //确定二维数组的行数和列数
            int line =CipherText.Length/Key.Length;
            int column =Key.Length;
            char[,] twodimarray1 = new char[line, column];
            char[,] twodimarray2 = new char[line, column];
            int[] array = new int[Key.Length];
            char[] plaintext = new char[CipherText.Length];
            //将密文按密钥给定的列数存入二维数组
            for (int i = 0; i < CipherText.Length; i++)
            {
                twodimarray1[i % line, i / line] = CipherText[i];
            }
            //按照密钥恢复相应列的顺序
            for (int i = 0; i < Key.Length; i++)
            {
                array[i] = Convert.ToInt16(Key[i]) - 49;
                for (int j = 0; j < line; j++)
                {
                    twodimarray2[j, array[i]] = twodimarray1[j, i];
                }
            }
            //将新的二维数组存入明文
            for (int i = 0; i < CipherText.Length; i++)
            {
                plaintext[i] = twodimarray2[i / column, i % column];
            }
            PlainText = new string(plaintext);
        }
    }
}
